package com.alpha.core.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Map;

/**
 * Json 辅助类
 *
 * @author chenruwan
 * @since 2022-01-01
 */
@Slf4j
@SuppressWarnings("unused")
public class JsonUtil {
    private JsonUtil() {
    }

    public static String toString(@Nonnull Object value) {
        try {
            return new ObjectMapper()
                    .setSerializationInclusion(JsonInclude.Include.NON_NULL)
                    .writeValueAsString(value);
        } catch (JsonProcessingException e) {
            return StringUtil.EMPTY;
        }
    }

    public static String toPrettyString(Object value) {
        try {
            return new ObjectMapper()
                    .setSerializationInclusion(JsonInclude.Include.NON_NULL)
                    .writerWithDefaultPrettyPrinter()
                    .writeValueAsString(value);
        } catch (JsonProcessingException e) {
            return StringUtil.EMPTY;
        }
    }

    @Nullable
    public static <T> T fromString(String json, Class<T> type) {
        try {
            if (json == null) {
                return null;
            }
            return new ObjectMapper().readValue(json, type);
        } catch (JsonProcessingException e) {
            log.warn("Caught Exception : ", e);
            return null;
        }
    }

    public static Map<String, Object> toMap(String json) {
        try {
            if (json == null) {
                return CollectionUtil.emptyMap();
            }

            @SuppressWarnings("unchecked")
            Map<String, Object> map = new ObjectMapper().readValue(json, Map.class);
            return map;
        } catch (JsonProcessingException e) {
            log.warn("Caught Exception : ", e);
            return CollectionUtil.emptyMap();
        }
    }
}
